﻿/****************************************************************************
*                                                                           *
* Copyright (c) Ionescu M. Marius. All rights reserved(2010).               *
*                                                                           *
****************************************************************************/

using System;
using System.Collections;
using System.Data;
using System.Drawing;
using System.IO;
using System.Security.Principal;
using System.Web;
using System.Web.UI.HtmlControls;

public partial class FSMS_ContentUpload : SessionPageBase
{
	private const string SCRIPT_TEMPLATE = "<" + "script " + "type=\"text/javascript\">window.parent.showUploadProgress('{0}', '{1}', {2});" + "<" + "/script" + ">";

	protected override void OnError(EventArgs e)
	{
		if (Server.GetLastError() is HttpException)
		{
			Tools.ScrieInLog(Server, "ERROR (ContentUpload.aspx.cs) [SessionID='" + Session.SessionID + "', UserName='" + this.User.Identity.Name + "', PathAndQuery='" + this.Request.Url.PathAndQuery + "', ImpersonationHelper.GetCurrentUser='" + ImpersonationHelper.GetCurrentUser() + "']:\r\nMessage: " + Server.GetLastError().Message + "\r\nContentLength: " + this.Request.ContentLength + "\r\nSource: " + Server.GetLastError().Source + "\r\nTargetSite: " + Server.GetLastError().TargetSite + "\r\nStackTrace: \r\n" + Server.GetLastError().StackTrace + "\r\nStackTrace2: \r\n" + (new System.Diagnostics.StackTrace(true)).ToString());

			lblError.Text = Server.GetLastError().Message;
			string script = string.Format(SCRIPT_TEMPLATE, Resources.DatabaseStrings.bError, txtClientID.Text, "true");
			ClientScript.RegisterStartupScript(this.GetType(), "uploadNotify", script);
			Server.ClearError();

			Session["UploadError"] = true;
		}
		else
			base.OnError(e);
	}

	private void Page_Load(object sender, EventArgs e)
	{
		if (!IsPostBack)
		{
			if (Session["UploadError"] != null)
			{
				Session["UploadError"] = null;
				string script = string.Format(SCRIPT_TEMPLATE, Resources.DatabaseStrings.FileSizeUpload + " " + Resources.DatabaseStrings.FileSizeUploadBig, "CustomUpload1", "true");
				ClientScript.RegisterStartupScript(this.GetType(), "uploadNotify", script);
			}
		}

		for (int i = 0; i < Convert.ToInt32(Request.QueryString["nr"]); ++i)
		{
			HtmlInputFile c = new HtmlInputFile();
			c.ID = "File" + i.ToString();
			c.Size = 40;
			ph.Controls.Add(c);
		}
		if (IsPostBack)
		{
			this.UploadFiles();
		}
	}

	private DataSet GetSystemConfigDataSet()
	{
		DataSet ds_SystemConfig = (DataSet)Session["ds_SystemConfig"];
		if (ds_SystemConfig == null)
		{
			ds_SystemConfig = Hipocrate.DB.DBConnection.GetData("System_Config_Select", new string[] { }, new object[] { });
			Session["ds_SystemConfig"] = ds_SystemConfig;
		}
		return ds_SystemConfig;
	}

	private bool UploadFiles()
	{
		bool bUseImpersonation = false;
		WindowsImpersonationContext impContext = null;

		DataSet ds_SystemConfig = GetSystemConfigDataSet();
		DataView dv = new DataView(ds_SystemConfig.Tables[0]);
		dv.RowFilter = "Code = 'UploadRootPath'";

		string _strRootPath = "";
		if (dv[0]["Name"].ToString().StartsWith("~"))
		{
			bUseImpersonation = false;
			_strRootPath = System.Web.HttpContext.Current.Request.MapPath(dv[0]["Name"].ToString());
		}
		else
		{
			bUseImpersonation = true;
			_strRootPath = dv[0]["Name"].ToString();
		}

//		string _strRootPath = System.Web.HttpContext.Current.Request.MapPath("~/Tools/Upload");
//		string _strRootPath = @"\\spetro004004.ww.omv.com\HD\NOB\FSMS";
		string script = "";
		System.Web.HttpFileCollection _files = System.Web.HttpContext.Current.Request.Files;
		System.Text.StringBuilder _message = new System.Text.StringBuilder(Resources.DatabaseStrings.FileUploaded + "<br>");

		try
		{
			bool bError = false;

			for (System.Int32 _iFile = 0; _iFile < _files.Count; _iFile++)
			{
				System.Web.HttpPostedFile _postedFile = _files[_iFile];
				System.String _fileName, _fileExtension, _filePath;

				_fileName = System.IO.Path.GetFileName(_postedFile.FileName);
				_filePath = _postedFile.FileName.Substring(0, _postedFile.FileName.LastIndexOf("\\") + 1);
				_fileExtension = System.IO.Path.GetExtension(_fileName);

				if (_postedFile.FileName == "")
					continue;

				if (_postedFile.ContentLength == 0 && _postedFile.FileName != "")
				{
					bError = true;
					_message.Append(" <font color=\"red\">" + Resources.DatabaseStrings.FilesContent + " <font color=\"black\">" + _fileName + "</font>" + " <font color=\"red\">" + Resources.DatabaseStrings.FilesContentEmpty + "</font><BR>");
				}
				else if (_postedFile.ContentLength > 20240000)
				{
					bError = true;
					_message.Append(" <font color=\"red\">" + Resources.DatabaseStrings.FileSizeUpload + " <font color=\"black\">" + _fileName + "</font>" + " <font color=\"red\">" + Resources.DatabaseStrings.FileSizeUploadBig + "</font><BR>");
				}

			}

			if (!bError)
			{
				for (System.Int32 _iFile = 0; _iFile < _files.Count; _iFile++)
				{
					System.Web.HttpPostedFile _postedFile = _files[_iFile];
					System.String _fileName, _fileExtension, _filePath;

					_fileName = System.IO.Path.GetFileName(_postedFile.FileName);
					_filePath = _postedFile.FileName.Substring(0, _postedFile.FileName.LastIndexOf("\\") + 1);
					_fileExtension = System.IO.Path.GetExtension(_fileName);

					if (_postedFile.FileName == "")
						continue;

					// creare lista directoare
					ArrayList _directoryList = new ArrayList { 
						//DateTime.Now.ToString("yyyy")
						
					};

					if (bUseImpersonation)
						impContext = ImpersonationHelper.StartImpersonate();

					// creare directoare
					string strServerPath = "";
					foreach (string s in _directoryList)
						if (s != "")
						{
							strServerPath += @"\" + s;
							if (!Directory.Exists(_strRootPath + strServerPath))
								Directory.CreateDirectory(_strRootPath + strServerPath);
						}

					string _fileNameServer = _fileName;
					//if (dv2[0]["FS_Name"] != System.DBNull.Value)
						_fileNameServer = _fileName;
					// salvare fisier
					_postedFile.SaveAs(_strRootPath + strServerPath + "/" + _fileNameServer);

					if (bUseImpersonation)
						ImpersonationHelper.StopImpersonate(impContext);

					DataSet ds_SMS = (DataSet)Session[Request.QueryString["smsSessionKey"]];
					ds_SMS.Tables[0].DefaultView[0]["FileName"] = _strRootPath + strServerPath + "/" + _fileNameServer; 

					_message.Append("<font color=\"red\">" + _fileName + "</font><BR>");
				}
			}
			script = string.Format(SCRIPT_TEMPLATE, (bError ? Resources.DatabaseStrings.bError : Resources.DatabaseStrings.FilesUploaded), txtClientID.Text, bError.ToString().ToLower());
			ClientScript.RegisterStartupScript(this.GetType(), "uploadNotify", script);

			lblError.Text = _message.ToString();
			return true;
		}
		catch (Exception ex)
		{
			Tools.ScrieInLog(Server, "ERROR (ContentUpload.aspx.cs) [SessionID='" + Session.SessionID + "', UserName='" + this.User.Identity.Name + "', ImpersonationHelper.GetCurrentUser='" + ImpersonationHelper.GetCurrentUser() + "']:\r\nMessage: " + ex.Message + "\r\nSource: " + ex.Source + "\r\nTargetSite: " + ex.TargetSite + "\r\nStackTrace: \r\n" + ex.StackTrace + "\r\nStackTrace2: \r\n" + (new System.Diagnostics.StackTrace(true)).ToString());

			lblError.ForeColor = Color.Red;
			lblError.Text = ex.Message;
			script = string.Format(SCRIPT_TEMPLATE, Resources.DatabaseStrings.bError, txtClientID.Text, "true");
			ClientScript.RegisterStartupScript(this.GetType(), "uploadNotify", script);
			return false;
		}
	}
}
